const CryptoJS = require('crypto-js');
import { JSEncrypt } from 'jsencrypt'

//Aes加密方法
export function AesEncrypt (word, keyStr) {
  var key = CryptoJS.enc.Utf8.parse(keyStr);//Latin1 w8m31+Yy/Nw6thPsMpO5fg==
  var srcs = CryptoJS.enc.Utf8.parse(word);
  var encrypted = CryptoJS.AES.encrypt(srcs, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 });
  return encrypted.toString();
}
//Aes解密方法
export function AesDecrypt (word, keyStr) {
  var key = CryptoJS.enc.Utf8.parse(keyStr);//Latin1 w8m31+Yy/Nw6thPsMpO5fg==
  var decrypt = CryptoJS.AES.decrypt(word, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 });
  return CryptoJS.enc.Utf8.stringify(decrypt).toString();
}

//Rsa加密方法
export function RsaEncrypt (word) {
  let pubKey = `-----BEGIN PUBLIC KEY-----
 MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCkuoiZut4NqmpIvap2e2mLHT4TkOSsUQZ8irHxEFaAL3GskYzrXmYzZolG+9Mk3C3hvUqTBf4YuNxV6RxLo4lxo9tapdktm0F2eqvG3ZKWdnOe4y0DkpYQrL/LxlhnXIjJgPfWj7UtWKSksMkEtrCQUj+9E2fBOfGisJoGWjKKOwIDAQAB
  -----END PUBLIC KEY-----`;
  var en = new JSEncrypt();
  en.setPublicKey(pubKey);
  return en.encrypt(word)
}

//Rsa解密方法
export function RsaDecrypt (word) {
  let priKey = `-----BEGIN RSA PRIVATE KEY-----
 MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKS6iJm63g2qaki9qnZ7aYsdPhOQ5KxRBnyKsfEQVoAvcayRjOteZjNmiUb70yTcLeG9SpMF/hi43FXpHEujiXGj21ql2S2bQXZ6q8bdkpZ2c57jLQOSlhCsv8vGWGdciMmA99aPtS1YpKSwyQS2sJBSP70TZ8E58aKwmgZaMoo7AgMBAAECgYBD8WgcODYUXuC9pfUkL1zl8ybCfTXEWRsazT39luaGsorpSZNdFS+ELdubOozpHCOUgzW6FHOskLrYeHCiRg6O9dOkIWO2TqIsQWJLYUR34CTTKCKNNRu6No4Qm5xdde7bDczMBohofWhIsD8E/yNyzBaZniWyd9yurAMrtqgb8QJBANziXxQ9bJTNQPJEC/wFOtfEeW14at8vCluaxeVv2p2EfhRknWBqNG7MXMgEpnWUdp8hmyMaOoOHmRi0mBEij0kCQQC+6rhpk+CY0VDSZNMjskN0XOQpCyxtMouEtZ5gmdHoPUUZ3DcKj83yckDNIAgqPlZVu9cE45Kcn9NR93wAHxljAkBIqJZKHCJ5mEMC7mtazYWbsF+ZKQFOxTSNCY6LeI3bPtgScT5rlsQEpmjmytDO4LVchzt3Aou49IPh4pYbHNkxAkB0MglBAKaOe76z/nde320ckjivHkTQxRWTFLKq2pOdxESdQ6EgRXuz1oPIFHnDtCL5lRR9vkAKIWANIBIRRNw/AkEAoMDjGllrUniDthx8Kl69jF3LrOCGrPYqNrsycAJSI7HZwTX4w/u7d/xMSqBZ1fwHQH7LcVEjG1cXI9M/2PEIrQ==
  -----END RSA PRIVATE KEY-----`;
  var en = new JSEncrypt();
  en.setPrivateKey(priKey);
  return en.decrypt(word)
}

//获取随机字符串
export function randomString (e) {
  e = e || 32;
  var t = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678",
    a = t.length,
    n = "";
  for (var i = 0; i < e; i++) n += t.charAt(Math.floor(Math.random() * a));
  return n
}

//传参加密
export function sendParam (param) {
  let randomStr = randomString(16)
  return {
    "requestData": AesEncrypt(JSON.stringify(param), randomStr),
    "encrypted": RsaEncrypt(randomStr)
  }
}

//出参解密
export function paramDecrypt (res) {
  let key = RsaDecrypt(res.encrypted)
  return JSON.parse(AesDecrypt(res.requestData, key))
}
